import BASE_URL from '../api/baseURL';
import store from '../store'; // 如果使用 Vuex 状态管理

const http = {
  async request(config) {
    const defaultConfig = {
      url: '',
      method: 'GET',
      data: {},
      header: {
        'Content-Type': 'application/json',
        'Authorization': ''
      },
      dataType: 'json'
    };

    // 合并配置
    const mergedConfig = { ...defaultConfig, ...config };

    // 设置请求头中的 Token
    if (store.state.user.token) {
      mergedConfig.header.Authorization = `Bearer ${store.state.user.token}`;
    }

    try {
      const res = await uni.request({
        url: `${BASE_URL}${mergedConfig.url}`,
        method: mergedConfig.method,
        data: mergedConfig.data,
        header: mergedConfig.header,
        dataType: mergedConfig.dataType
      });

      const [error, response] = res;

      if (error) {
        console.error('请求错误:', error);
        // 处理网络错误
        if (error.errCode === 'NETWORK_ERR') {
          uni.showToast({
            title: '网络连接失败，请检查网络设置',
            icon: 'none'
          });
        }
        return Promise.reject(error);
      }

      // 处理业务错误
      if (response.statusCode !== 200) {
        uni.showToast({
          title: response.data.message || '请求失败',
          icon: 'none'
        });
        return Promise.reject(response.data);
      }

      return response.data;
    } catch (err) {
      console.error('请求异常:', err);
      uni.showToast({
        title: '请求异常',
        icon: 'none'
      });
      return Promise.reject(err);
    }
  },

  get(url, data = {}) {
    return this.request({ url, method: 'GET', data });
  },

  post(url, data = {}) {
    return this.request({ url, method: 'POST', data });
  },

  put(url, data = {}) {
    return this.request({ url, method: 'PUT', data });
  },

  delete(url, data = {}) {
    return this.request({ url, method: 'DELETE', data });
  },

  upload(url, filePath, name = 'file', data = {}) {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: `${BASE_URL}${url}`,
        filePath: filePath,
        name: name,
        formData: data,
        header: {
          'Authorization': `Bearer ${store.state.user.token}`
        },
        success: (res) => {
          const result = JSON.parse(res.data);
          if (res.statusCode === 200) {
            resolve(result);
          } else {
            uni.showToast({
              title: result.message || '上传失败',
              icon: 'none'
            });
            reject(result);
          }
        },
        fail: (err) => {
          console.error('上传失败:', err);
          uni.showToast({
            title: '上传失败，请检查网络',
            icon: 'none'
          });
          reject(err);
        }
      });
    });
  }
};

export default http;